package com.example.validated.annotation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Objects;

/**
 * @author ww
 */
public class EnumValueValidator implements ConstraintValidator<EnumValue, Object> {

    private String[] strValues;
    private int[] intValues;

    @Override
    public void initialize(EnumValue constraintAnnotation) {
        strValues = constraintAnnotation.strValues();
        intValues = constraintAnnotation.intValues();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if(value instanceof String) {
            for (String s:strValues) {
                if(s.equals(value)){
                    return true;
                }else {
                    //如果是多个，隔开也给放行
                    String[] values = String.valueOf(value).split(",");
                    ArrayList<String> list = new ArrayList(Arrays.asList(strValues));
                    boolean  allok = true;
                    for (String s1 : values) {
                        if (!list.contains(s1)){
                            allok = false;
                        }
                    }
                    return allok;
                }
            }
        }else if(value instanceof Integer){
            for (Integer s:intValues) {
                if(Objects.equals(s,value)){
                    return true;
                }
            }
        }
        return false;

    }
}
